<?php
 
/**
* The module of domains (functions)
* Модуль доменов (функции)
* @author IT studio IRBIS-team
* @copyright © 2009 IRBIS-team
*/
/////////////////////////////////////////////////////////

/**
* Generation of page of an error at access out of system
* Генерация страницы ошибки при доступе вне системы
*/
    if(!defined('IRB_KEY'))
    {
       header("HTTP/1.1 404 Not Found");      
       exit(file_get_contents('../../404.html'));
    } 
//////////////////////////////////////////////////////////
   
function getDomain($dom_id)
{
	if(!empty($dom_id))
	{
		$query = mysqlQuery("SELECT d.id as d_id, 
									d.chief as d_chief,
									d.caption as d_caption, 
									d.description as d_description, 
									d.hash as d_hash,
									d.country as d_country, 
									d.region as d_region, 
									d.city as d_city,
									d.creator as d_creator,
									d.update_date as d_update_date,
									d.create_date as d_create_date
							FROM 
									`". IRB_DBPREFIX ."domains` d
							WHERE
									d.id = '".$dom_id."'
							");
		return mysql_fetch_assoc($query);
	}
}

function getDomainUsers($dom_id)
{
	if(!empty($dom_id))
	{
		$query = mysqlQuery("SELECT u.id as u_id, 
									u.name as u_name, 
									u.surname as u_surname, 
									u.login as u_login, 
									sdlu.role as u_role
							FROM 
								`". IRB_DBPREFIX ."user` u,
								`". IRB_DBPREFIX ."dom_link_user` sdlu
							WHERE
								sdlu.domain_id = '".$dom_id."'
							AND
								u.id = sdlu.user_id
							ORDER by u.id
							");
		
		if(mysql_num_rows($query) > 0)
		{
			$user_array = array();
			
			while($row = mysql_fetch_assoc($query))
				$user_array[] = array(	
										'u_id' => $row['u_id'],
										
										'u_caption' => (empty($row['u_surname']) AND empty($row['u_name']))?$row['u_login']:$row['u_surname']." ".$row['u_name'],
										
										'u_role' => $row['u_role']
										);
			
			return $user_array;
		}
		
		
	}
}

function getDomainAssets($dom_id){
	if(!empty($dom_id))
	{
		$query = mysqlQuery("SELECT a.id as a_id, a.caption as a_caption
							FROM 
								`". IRB_DBPREFIX ."assets` a,
								`". IRB_DBPREFIX ."asset_link_dom_user` aldu
							WHERE
								aldu.dom_id = '".$dom_id."'
							AND
								a.id = aldu.asset_id
							ORDER by a.id
							");
		
		if(mysql_num_rows($query) > 0)
		{
			$asset_array = array();
			
			while($row = mysql_fetch_assoc($query))
				$asset_array[] = $row;
			
			return $asset_array;
		}
		
		
	}

}


function userRoleInDomain($user_id, $dom_id)
{
	if(!empty($user_id) AND !empty($dom_id))
	{
		$query = mysqlQuery("SELECT sdlu.role as user_role
							FROM 
								`". IRB_DBPREFIX ."dom_link_user` sdlu
							WHERE
								sdlu.user_id = '".$user_id."'
							AND
								sdlu.domain_id = '".$dom_id."'							
							");
		$arr = mysql_fetch_assoc($query);
		return $arr['user_role'];
	}
}
function sendRequest($user_id,$dom_id)
{
	if($user_id AND $dom_id){
	
			$status = userRequestStatusToDomain($user_id,$dom_id);
			
			if($status == 'not')
			{
				mysqlQuery("INSERT INTO 
									`". IRB_DBPREFIX ."dom_requests`
							SET 
								`dom_id` = '".$dom_id."',
								`user_id` = '".$user_id."',
								`create_date` = CURRENT_TIMESTAMP()");
				
				if(mysql_affected_rows() > 0)
					$info[] = 'Заявка успешно отправлена';
				else
					$info[] = 'Не удалось отправить заявку по тех.причинам.';
			}
			elseif($status == 'none')
				$info[] = 'Ваша заявка в рассмотрении.';
			elseif($status == 'denied')
				$info[] = 'Ваша заявка уже была отклонена.';
			elseif($status == 'accepted')
				$info[] = 'Ваша заявка уже была одобрена.';

	}
	else
		$info[] = 'Нет ид пользователя или ид домена';

	return $info;
}

function acquireRequest($request_id,$request_status, $user_id, $dom_id)
{
	switch($request_status){
		
		case 'accept':
			$is_in_domain = mysqlQuery("SELECT * 
										FROM `soc_dom_link_user` 
										WHERE 
											user_id=".$user_id."
										AND
											domain_id=".$dom_id."											
										");
			if(mysql_num_rows($is_in_domain) == 0)
			{
				mysqlQuery("INSERT INTO `soc_dom_link_user` 
								SET 
									user_id=".$user_id.",
									domain_id=".$dom_id.",
									role=10
								");
			
				if(mysql_affected_rows() > 0)
						$info[] = 'Пользователь включен в домен';
					else
						$info[] = 'Не удалось включить в домен по тех.причинам.';
						
				mysqlQuery("UPDATE `soc_dom_requests` dr
								SET accept_status='accepted'
								WHERE dr.id=".$request_id."");
				
				if(mysql_affected_rows() > 0)
						$info[] = 'Заявка отмечена "принято".';
					else
						$info[] = 'Не удалось отметить заявку.';
			}
			else
			{
				$info[] = 'Пользователь уже есть в домене.';	
				
				mysqlQuery("DELETE FROM `soc_dom_requests`
								WHERE id=".$request_id."");
				
				if(mysql_affected_rows() > 0)
						$info[] = 'Левая заявка удалена из БД.';
					else
						$info[] = 'Не получилось удалить левую заявку из БД.';
			}
			break;
		
		case 'deny':
			mysqlQuery("UPDATE `soc_dom_requests` dr
							SET accept_status='denied'
							WHERE dr.id=".$request_id."");
			break;
		}

	return $info;
}

function sendInvite($inviter_id, $user_email, $cur_dom_id)
{
	if(!$user_email) 
		$info[] = IRB_LANG_EMPTY_EMAIL; 
						
	elseif(!preg_match("/^[a-z0-9_.-]+@([a-z0-9]+.)+[a-z]{2,6}$/i", $user_email)) 
			$info[] = IRB_LANG_INVALID_EMAIL;
			
	else
	{
		$user_query = mysqlQuery("SELECT u.id as u_id, u.name as u_name, u.surname as u_surname
							FROM
								`". IRB_DBPREFIX ."user` u
							WHERE
								u.email = '".$user_email."'
							");
		if(mysql_num_rows($user_query) > 0)
		{
			$user = mysql_fetch_assoc($user_query);
			$is_invite = mysqlQuery("SELECT di.id as di_id, 
											di.inviter_id as di_inviter_id, 
											di.create_date as di_create_date
									FROM
										`". IRB_DBPREFIX ."dom_invites` di
									WHERE
										di.dom_id = '".$cur_dom_id."'
									AND
										di.user_id = '".$user['u_id']."'
									");
			if(mysql_num_rows($is_invite) > 0)
			{
				$invite = mysql_fetch_assoc($is_invite);
				$info[] = "Пользователю ".$user['u_surname']." ".$user['u_name']." уже было выслано приглашение ".$invite['di_create_date'].".";
			}
			else
			{
				mysqlQuery("INSERT INTO 
									`". IRB_DBPREFIX ."dom_invites`
							SET 
								`inviter_id` = '".$inviter_id."',
								`dom_id` = '".$cur_dom_id."',
								`user_id` = '".$user['u_id']."',
								`create_date` = CURRENT_TIMESTAMP()
							");
				
				if(mysql_affected_rows() > 0)
				{
					mysqlQuery("INSERT INTO 
									`". IRB_DBPREFIX ."dom_link_user`
								SET
									`user_id` = '".$user['u_id']."',
									`domain_id` = '".$cur_dom_id."',
									`role` = '1'
								");
					
					$info[] = "Пользователю ".$user['u_surname']." ".$user['u_name']." выслано приглашение, назначены права \"Прохожего\" в данном домене.";
				}
				else
				{
					$info[] = "По техническим причинам невозможно выслать приглашение.";
				}
			}
		}
		else
			$info[] = "Такого пользователя нет в зарегистрированных.";
	}
}
function userRequestsToDomain($dom_id)
{
	$requests = mysqlQuery("SELECT 	dr.id, 
									dr.user_id,
									dr.create_date,
									u.name as u_name,
									u.surname as u_surname,
									u.login as u_login
							FROM	
								`". IRB_DBPREFIX ."dom_requests` dr,
								`". IRB_DBPREFIX ."user` u
							WHERE
								dr.dom_id=".$dom_id."
							AND
								u.id=dr.user_id
							AND
								dr.accept_status ='none'");
	if(mysql_num_rows($requests) > 0)
			{
				while ($row = mysql_fetch_assoc($requests)) 
				{
					$urt[] = array(
								'id' => $row['id'],
								'user_id' => $row['user_id'],
								'create_date' => $row['create_date'],
								'u_caption' => (empty($row['u_surname']) AND empty($row['u_name']))?$row['u_login']:$row['u_surname']." ".$row['u_name']
							);
				
				}
				return $urt;
			}
}

function userRequestStatusToDomain($user_id,$dom_id){
	
	$request = mysqlQuery("SELECT dr.accept_status
	
							FROM
								`". IRB_DBPREFIX ."dom_requests` dr
							WHERE
								dr.dom_id=".$dom_id."
							AND
								dr.user_id=".$user_id."
						");

	if(mysql_num_rows($request) > 0)
			{
				$status = mysql_fetch_assoc($request);
				
				return $status['accept_status'];
			}
	else 
		return  'not';
	
}
function userInvitesFromDomains($user_id)
{
	$invites = mysqlQuery("SELECT d.id, d.caption
							FROM 
								`". IRB_DBPREFIX ."domains` d,
								`". IRB_DBPREFIX ."dom_invites` di
							WHERE
								di.dom_id = d.id
							AND
								di.user_id = '".$user_id."'
							AND
								di.accept_status = 'none'
							");
	
	if(mysql_num_rows($invites) > 0)
	{
		while ($row_i = mysql_fetch_assoc($invites)) 
			$dom_invites[] = htmlChars($row_i);
		
		return $dom_invites;
	}
	
}

function getDomains(){
	$domains = array();
	
	$res = mysqlQuery("SELECT 	d.id,
								d.caption
																
						FROM  `". IRB_DBPREFIX ."domains` d
						
						");	
	
	if(mysql_num_rows($res) > 0)
		{
			while ($row = mysql_fetch_assoc($res))
				{
					$domains[] = htmlChars($row);
				}
		}   
	
	return $domains;
}

function leaveDomain($user_id,$dom_id){
	if($user_id AND $dom_id){
		
		mysqlQuery("DELETE FROM `soc_dom_requests` WHERE user_id=".$user_id." AND dom_id=".$dom_id." AND accept_status='accepted'");
		
		if(mysql_affected_rows() > 0)
			$info[] = 'Заявка удалена.';
		else
			$info[] = 'Заявку удалить не вышло.';
		
		mysqlQuery("DELETE FROM `soc_dom_link_user` WHERE user_id=".$user_id." AND domain_id=".$dom_id."");
		
		if(mysql_affected_rows() > 0)
			$info[] = 'Связь с доменом удалена.';
		else
			$info[] = 'Не получилось удалить связь с доменом.';
	}
	else
		$info[] = "Нет user_id или dom_id";
		
	return $info;
}

function is_in_array($id,$array)
{
	if(!empty($array))
	{
		foreach($array as $a_key => $a)
		{
			if($a['id'] == $id) return 1;
		}
	}
	return 0;
}